/*
 * @Author: your name
 * @Date: 2021-10-18 20:05:49
 * @LastEditTime: 2021-10-18 20:52:59
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bigdate\src\views\admin\functionPage\markeditor\imgAdapter.ts
 */
import { gettoken } from '@/ntils/hooks'

const getTokenfunc = () => {
    gettoken.get({
        url: '/token/dev/ijrDsqFix838Gh3wGO3F77FSW94BwcLXprJ4APSp3XQ26xsUHTi0jcb1hoBt',
    }).then(res => {
        sessionStorage.setItem('token', res.data)
    }).catch(err => {
        console.log(err)
    })
}
getTokenfunc()
// 从官网拷贝适配器
export class MyUploadAdapter {
    xhr

    loader

    token

    constructor(loader) {
        this.loader = loader
    }

    upload() {
        return this.loader.file
        .then(file => new Promise((resolve, reject) => {
            this._initRequest()
            this._initListeners(resolve, reject, file)
            this._sendRequest(file)
        }))
    }

    // Aborts the upload process.
    abort() {
        if (this.xhr) {
            this.xhr.abort()
        }
    }

    _initRequest() {
        let tokens:string = sessionStorage.getItem('token')
        const xhr = this.xhr = new XMLHttpRequest()
        // 代理使用vue做代理
        xhr.open('POST', '/upload/easyimage/upload/', true)
        // token 必须存在的  可能会过期

        xhr.setRequestHeader('Authorization', tokens)
    }

    // Initializes XMLHttpRequest listeners.
    _initListeners(resolve, reject, file) {
        const xhr = this.xhr
        const loader = this.loader
        const genericErrorText = `Couldn't upload file: ${file.name}.`

        xhr.addEventListener('error', () => reject(genericErrorText))
        xhr.addEventListener('abort', () => reject())
        xhr.addEventListener('load', () => {
            const response = xhr.response
            if (!response || response.error) {
                getTokenfunc()
                return reject(response && response.error ? response.error.message : genericErrorText)
            }
            let url = JSON.parse(response)
            console.log(url.default)
            resolve({
                default: url.default,
            })
        })
    }

    _sendRequest(file) {
        // Prepare the form data.
        const data = new FormData()
        data.append('file', file)
        this.xhr.send(data)
    }
}